home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Diamond Collection / The Diamond Collection (Software Vault)(Digital Impact).ISO / cdr47 / lzpip103.zip / BITS.C next >
Text File  |  1994-06-02  |  2KB  |  94 lines

  1. #include <stdio.h>
  2. #include "modern.h"
  3. #include "stdinc.h"
  4. #include "zalloc.h"
  5. #include "zipdefs.h"
  6. #include "zipguts.h"
  7. #include "lzpipe.h"
  8.  
  9. static unsigned bitbuff;
  10. static int boffset;
  11.  
  12. #ifdef DEBUG
  13. ulg bits_sent;   /* bit length of the compressed data */
  14. #endif
  15.  
  16. void bi_init() /* Initialize the bit string routines. */
  17. {
  18.    bitbuff = 0;
  19.    boffset = 0;
  20. #ifdef DEBUG
  21.    bits_sent = 0L;
  22. #endif
  23. }
  24.  
  25. int send_bits(value, length) /* Send a value on a given number of bits. */
  26. unsigned value; /* value to send */
  27. int length;     /* number of bits: length =< 16 */
  28. {
  29. #ifdef DEBUG
  30.    Tracevv((stderr," l %2d v %4x ", length, value));
  31.    Assert(length > 0 && length <= 15, "invalid length");
  32.    Assert(boffset < 8, "bad offset");
  33.    bits_sent += (ulg)length;
  34. #endif
  35.    bitbuff |= value << boffset;
  36.    if ((boffset += length) >= 8) {
  37.       if (putbyte(bitbuff) == EOF) return -1;
  38.       value >>= length - (boffset -= 8);
  39.       if (boffset >= 8) {
  40.          boffset -= 8;
  41.          if (putbyte(value) == EOF) return -1;
  42.          value >>= 8;
  43.       }
  44.       bitbuff = value;
  45.    }
  46.    return 0;
  47. }
  48.  
  49. /* Write out any remaining bits in an incomplete byte. */
  50. int bi_windup()
  51. {
  52.    Assert(boffset < 8, "bad offset");
  53.    if (boffset) {
  54.       if (putbyte(bitbuff) == EOF) return -1;
  55.       boffset = 0;
  56.       bitbuff = 0;
  57. #ifdef DEBUG
  58.       bits_sent = (bits_sent+7) & ~7;
  59. #endif
  60.    }
  61.    return 0;
  62. }
  63.  
  64. int bi_putsh(x)
  65. unsigned short x;
  66. {
  67.    return (putbyte(x&255)==EOF || putbyte((x>>8)&255)==EOF) ? -1 : 0;
  68. }
  69.  
  70. /* Copy a stored block to the zip file, storing first the length and its
  71.    one's complement if requested. */
  72. int copy_block(buf, len, header)
  73. char far *buf; /* the input data */
  74. unsigned len;  /* its length */
  75. int header;    /* true if block header must be written */
  76. {
  77.    /* align on byte boundary */
  78.    if (bi_windup() != 0) return -1;
  79.  
  80.    if (header) {
  81.       if (bi_putsh(len) != 0 || bi_putsh(~len) != 0) return -1;
  82. #ifdef DEBUG
  83.       bits_sent += 2*16;
  84. #endif
  85.    }
  86.    while (len--) {
  87.       if (putbyte(*buf++) == EOF) return -1;
  88.    }
  89. #ifdef DEBUG
  90.    bits_sent += (ulg)len<<3;
  91. #endif
  92.    return 0;
  93. }
  94.